package com.example.yuejian11.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.example.yuejian11.R;
import com.example.yuejian11.adapter.MainActivityAdapter;
import com.example.yuejian11.adapter.MainBSAdapter;
import com.example.yuejian11.adapter.MainMasterAdapter;
import com.example.yuejian11.bean.ActivityListEntity;
import com.example.yuejian11.bean.BsEntity;
import com.example.yuejian11.bean.MasterEntity;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MainFragment extends Fragment {

    private static final String TAG = "MainFragment";
    RecyclerView.Adapter adapter;

    @BindView(R.id.recy)
    RecyclerView recyclerView;
    LinearLayoutManager layoutManager;
    Handler handler_activity = new mHandler();
    private String flag;
    private Context context;
    private Unbinder unbinder;

    public MainFragment setFlag(String flag) {
        this.flag = flag;
        return this;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    //@NonNull指明一个参数，字段或者方法的返回值不可以为null
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //设置布局
        View view = inflater.inflate(R.layout.fragment_main_rv, container, false);
        //绑定视图
        unbinder = ButterKnife.bind(this, view);
        //获取context
        context = view.getContext();
        initView();
        return view;
    }

    private void initView() {
        layoutManager = new LinearLayoutManager(context);//创建布局管理器
        switch (flag) {
            case "activity":
                setActivity();
                break;
            case "master":
                setMaster();
                break;
            case "bs":
                setBS();
                break;
            case "my":
                break;
            default:
                break;
        }


    }

    private void setBS() {
        EasyHttp.get("yuejian6/public/index.php/json/recentgame/lists")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String data) {

                        Message msg = Message.obtain(); // 实例化消息对象
                        msg.what = 2; // 消息标识
                        msg.obj = data; // 消息内容存放

                        handler_activity.sendMessage(msg);
                    }

                    @Override
                    public void onError(ApiException error) {
                        Log.d(TAG, "onFailed: " + error);
                    }
                });
    }

    private void setMaster() {
        EasyHttp.get("yuejian6/public/index.php/json/master/lists")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String data) {

                        Message msg = Message.obtain(); // 实例化消息对象
                        msg.what = 1; // 消息标识
                        msg.obj = data; // 消息内容存放

                        handler_activity.sendMessage(msg);
                    }

                    @Override
                    public void onError(ApiException error) {
                        Log.d(TAG, "onFailed: " + error);
                    }
                });
    }

    public void setActivity() {
        Log.d(TAG, "setActivity:  start");
        EasyHttp.get("yuejian6/public/index.php/json/activity/lists")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String data) {

                        Message msg = Message.obtain(); // 实例化消息对象
                        msg.what = 0; // 消息标识
                        msg.obj = data; // 消息内容存放

                        handler_activity.sendMessage(msg);
                    }

                    @Override
                    public void onError(ApiException error) {
                        Log.d(TAG, "onFailed: " + error);
                    }
                });
    }

    // 步骤1：自定义Handler子类（继承Handler类） & 复写handleMessage（）方法
    class mHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:

                    List<ActivityListEntity> activityListEntities = null;

                    try {
                        //msg.obj ，json数据（msg.obj  Object类型转换成string）
                        activityListEntities = JSON.parseArray(msg.obj.toString(), ActivityListEntity.class);
                    } catch (Exception e) {

                    }

                    if (activityListEntities == null) {
                        return;
                    }
                    //创建adapter适配器
                    adapter = new MainActivityAdapter(context, activityListEntities, R.layout.activity_item);

                    break;
                case 1:


                    List<MasterEntity> masterEntities = null;

                    try {
                        masterEntities = JSON.parseArray(msg.obj.toString(), MasterEntity.class);
                    } catch (Exception e) {

                    }
                    if (masterEntities == null) {
                        return;
                    }

                    adapter = new MainMasterAdapter(context, masterEntities, R.layout.master_item);

                    break;
                case 2:
                    List<BsEntity> bsEntities = null;

                    try {
                        bsEntities = JSON.parseArray(msg.obj.toString(), BsEntity.class);
                    } catch (Exception e) {

                    }
                    if (bsEntities == null) {
                        return;
                    }
                    //创建adapter适配器
                    adapter = new MainBSAdapter(context, bsEntities, R.layout.main_bs_item);
                    break;
                case 3:
                    break;
            }


            //设置布局管理器
            recyclerView.setLayoutManager(layoutManager);
            //设置为垂直布局，这也是默认的
            layoutManager.setOrientation(OrientationHelper.VERTICAL);
            //设置Adapter
            recyclerView.setAdapter(adapter);
            //设置增加或删除条目的动画
            recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
            recyclerView.setItemAnimator(new DefaultItemAnimator());


        }


    }

}
